package it.polimi.travelDream.ejb.servlet;

import it.polimi.travelDream.ejb.interfaces.ExcursionMgrRemote;

import java.io.IOException;
import java.util.Map;
import java.lang.Object;

import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;



/**
 * Servlet implementation class TravelServlet
 */
@WebServlet("/AddExcursion")
public class AddExcursion extends HttpServlet {
	private static final long serialVersionUID = 1L;
	DateFormat format = new SimpleDateFormat("dd/MM/yyyy");
	
	
	@EJB
	ExcursionMgrRemote umr;

	public AddExcursion() {
		super();
	}

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {	
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		Map<String, String[]> mappa = request.getParameterMap();
		System.out.println(mappa.get("name")[0]);
		format.setLenient(false);
		/*Empty Fields Check*/
		if (mappa.get("name")[0].isEmpty() ||mappa.get("description")[0].isEmpty() || mappa.get("totalCost")[0].isEmpty() || mappa.get("duration")[0].isEmpty() || mappa.get("availabilityPax")[0].isEmpty() || mappa.get("availabilityDay")[0].isEmpty())
		 {
			request.setAttribute("message","ricorda di inserire tutti i campi");
			request.getRequestDispatcher("/BPAddExcursion.jsp").forward(request, response); 
		 }else
		 {
			 try {
				 Integer.parseInt(mappa.get("totalCost")[0]);
				 Integer.parseInt(mappa.get("availabilityPax")[0]);
				 format.parse(mappa.get("availabilityDay")[0]);
				 /*Excursion Insertion*/
					umr.addExcursion(mappa.get("name")[0], mappa.get("description")[0],mappa.get("totalCost")[0], mappa.get("duration")[0],mappa.get("availabilityPax")[0],mappa.get("availabilityDay")[0]);
					/*Next JSP parameters and call*/
					request.setAttribute("message","Excursion "+ mappa.get("name")[0] +" succesfully registered.");
					request.getRequestDispatcher("/BPAdvice.jsp").forward(request, response); 
				 
				 } catch (ParseException e) {
				 
					 request.setAttribute("message","date must be in dd/mm/yyyy format, total cost and availability must be a number");
						request.getRequestDispatcher("/BPAddExcursion.jsp").forward(request, response); 
					 
				 }

			 		 
			 
			
		}
	}
}
